import { createSlice , createAsyncThunk } from '@reduxjs/toolkit';
import { setTheme } from '../theme';

// 异步操作的方式一
// 这是一个 ActionCreator 函数
export const loadOthers = createAsyncThunk('others/getOthers', (payload: object, thunkAPI) => {
  fetch('xx://xxx.xxx.xx', { body: JSON.stringify(payload) })
    .then(response => response.json())
    .then(response => thunkAPI.dispatch(setTheme(response)))
});

// 异步操作的方式二
export const loadOther = createAsyncThunk('others/getOther', (payload: object) => {
  return fetch('xx://xxx.xxx.xx', { body: JSON.stringify(payload) })
    .then(response => response.json())
});

const Others_FEATURE_KEY = 'others';


const { actions, reducer } = createSlice({
  name: Others_FEATURE_KEY,
  initialState: [] as any[],
  reducers: { // 接受同步 action
    setOthers (state, action) {
      action.payload.forEach((item: any) => {
        state.push(item);
      })
    }
  },
  // 接受异步的 action
  extraReducers: {
    [loadOther.fulfilled.toString()]: (state, action) => {
      action.payload.forEach((item: any) => {
        state.push(item);
      });
    },
    [loadOther.pending.toString()]: (state, action) => {
      console.log(state, action);
    },
    [loadOther.rejected.toString()]: (state, action) => {
      console.log(state, action);
    }
  }
})

export const { setOthers } = actions;

export default reducer;
